"""
微信小程序相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.common import ApiResponse
from app.models.user import User
from app.services.wechat import wechat_service

router = APIRouter()


class PhoneCodeRequest(BaseModel):
    """手机号授权请求"""
    code: str


class PhoneNumberResponse(BaseModel):
    """手机号响应"""
    phoneNumber: str
    purePhoneNumber: str
    countryCode: str


@router.post("/get-phone-number", response_model=ApiResponse[PhoneNumberResponse])
async def get_phone_number(
    request: PhoneCodeRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取用户手机号（需要用户授权）
    
    前端调用示例:
    ```javascript
    // 在 button 组件中使用
    <button open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">
      获取手机号
    </button>
    
    // 处理函数
    handleGetPhoneNumber(e) {
      const code = e.detail.code
      if (code) {
        // 调用后端接口
        api.post('/wechat/get-phone-number', { code })
      }
    }
    ```
    """
    # 获取 access_token
    access_token = await wechat_service.get_access_token()
    if not access_token:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取微信 access_token 失败"
        )
    
    # 获取手机号
    phone_data = await wechat_service.get_phone_number(request.code, access_token)
    if not phone_data:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="获取手机号失败"
        )
    
    # 更新用户手机号
    current_user.phone = phone_data["purePhoneNumber"]
    db.commit()
    
    return ApiResponse(
        data=PhoneNumberResponse(**phone_data)
    )


@router.get("/user-info", response_model=ApiResponse[dict])
async def get_wechat_user_info(
    current_user: User = Depends(get_current_user)
):
    """
    获取微信用户信息
    
    返回用户的微信相关信息
    """
    return ApiResponse(
        data={
            "hasWechat": bool(current_user.wechat_openid),
            "hasPhone": bool(current_user.phone),
            "openid": current_user.wechat_openid
        }
    )

